package listdemo;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

class Students {

    private String name;
    private String gender;
    private int age;

    public Students(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }
}
public class ListSortByComparatorDemo {

    public static void main(String[] args) {
        List list = new LinkedList();
        Students s1 = new Students("张三", "男", 20);
        Students s2 = new Students("李四", "女", 18);
        Students s3 = new Students("王五", "男", 21);
        Students s4 = new Students("赵六", "女", 22);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        //匿名内部类实现排序
        Collections.sort(list, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                int diff = p1.getAge() - p2.getAge();
                if (diff > 0) {
                    return 1;
                } else if (diff < 0) {
                    return -1;
                }
                return 0; //相等为0
            }
        });

        for (Object obj : list) {
            System.out.println(obj);
        }
    }

}
